#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/11/15 10:07
# @Author : 闫峰
# @File    : multithreaded.py
from concurrent.futures import ThreadPoolExecutor, as_completed, wait
from functools import partial


def multithreaded_args(max_workers, func_name, task_list):
    executor = ThreadPoolExecutor(max_workers=max_workers)
    tasks = []
    for i in task_list:
        # 使用funools.partial函数创建一个新的函数，将参数绑定到函数中
        new_task = partial(func_name, *i)
        # executor.submit(new_task)
        tasks.append(executor.submit(new_task))
    # 处理已完成的任务
    for future in as_completed(tasks):
        try:
            result = future.result()
            # 处理任务执行的结果
            # print(result)
        except Exception as e:
            # 处理任务执行出的异常
            print(f"任务{i}执行出现异常，参数为{new_task.args}")
            raise
    done, not_done = wait(tasks, return_when='ALL_COMPLETED')
    # 关闭线程池
    executor.shutdown()


def multithreaded_args(max_workers, func_name, task_list):
    executor = ThreadPoolExecutor(max_workers=max_workers)
    tasks = executor.map(lambda args:func_name(*args),task_list)
    # 处理已完成的任务
    for future in as_completed(tasks):
        try:
            result = future.result()
            # 处理任务执行的结果
            # print(result)
        except Exception as e:
            # 处理任务执行出的异常
            # print(f"任务执行出现异常: {e}")
            exc_info = future.exception()
            if exc_info:
                print(f"异常信息：{exc_info},任务参数：{future.args}")
            raise
    done, not_done = wait(tasks, return_when='ALL_COMPLETED')
    # 关闭线程池
    executor.shutdown()


def multithreaded(max_workers, func_name, task_list):
    executor = ThreadPoolExecutor(max_workers=max_workers)
    tasks = []
    for i in task_list:
        # 使用funools.partial函数创建一个新的函数，将参数绑定到函数中
        new_task = partial(func_name, i)
        # executor.submit(new_task)
        tasks.append(executor.submit(new_task))
    # 处理已完成的任务
    for future in as_completed(tasks):
        try:
            result = future.result()
            # 处理任务执行的结果
            print(result)
        except Exception as e:
            # 处理任务执行出的异常
            print(f"任务{i}执行出现异常，参数为{new_task.args}")
            raise e
    done, not_done = wait(tasks, return_when='ALL_COMPLETED')
    # 关闭线程池
    executor.shutdown()